package com.meis.widget.mobike;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.StackLayout;
import ohos.agp.render.Canvas;
import ohos.app.Context;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * desc:JBox2D运用-打造摩拜单车贴纸动画效果
 * author: wens
 * date: 2018/6/6.
 */
public class MoBikeView extends StackLayout implements Component.DrawTask, ComponentContainer.ArrangeListener, Component.EstimateSizeListener {

    private MoBike mMobike;

    public MoBikeView(@NotNull Context context) {
        this(context, null);
    }

    public MoBikeView(@NotNull Context context, @Nullable AttrSet attrs) {
        this(context, attrs, "");
    }

    public MoBikeView(@NotNull Context context, @Nullable AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mMobike = new MoBike(this);

        setArrangeListener(this);
        setEstimateSizeListener(this);

        addDrawTask(this);
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {
        mMobike.onSizeChange(EstimateSpec.getSize(i), EstimateSpec.getSize(i1));
        return false;
    }

    @Override
    public boolean onArrange(int left, int top, int width, int height) {
        for (int i = 0; i < getChildCount(); i++) {
            Component child = getComponentAt(i);
            int wid = child.getEstimatedWidth();
            int hei = child.getEstimatedHeight();
            child.arrange(width / 2 - (left + wid / 2), height / 2 - (top + hei / 2), wid, hei);
        }
        mMobike.onLayout(false);
        return false;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        mMobike.onDraw();
    }

    public MoBike getMobike() {
        return mMobike;
    }

    public void onSensorChanged(float x, float y) {
        mMobike.onSensorChanged(x, y);
    }

    public void onRandomChanged() {
        mMobike.onRandomChanged();
    }
}
